
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.Source;
import protocol.meta.Subject;
import protocol.transactions.TransactionGetSourceInfoList;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.adapter.AdapterInfo;
import com.netease.xone.itemview.RenderSourceView;
import com.netease.xone.widget.LoadingImageView;
import com.netease.xone.widget.listview.LoadingListView;

import db.XoneDBTables.AppInfoTable;
import db.manager.ManagerAccount;
import db.manager.ManagerAppInfo;

public class FragmentSubjectDetail extends FragmentBase implements LoaderCallbacks<Cursor> {

    public static FragmentSubjectDetail newInstance(int subjectId, String subjectName) {
        FragmentSubjectDetail f = new FragmentSubjectDetail();
        Bundle b = new Bundle();
        b.putInt(XoneConsts.BUNDLE_KEY.SUBJECT_ID, subjectId);
        b.putString(XoneConsts.BUNDLE_KEY.SUBJECT_NAME, subjectName);
        f.setArguments(b);
        return f;
    }

    private int mSubjectId;
    private String mSubjectName;
    private Subject mSubject;
    private int mCurrentPage;
    // Tid
    private int mSubjectTid;
    private int mSubjectInfoTid;
    // Views
    private LoadingListView mLoadingList;// 总体listview
    // 头图部分
    private LoadingImageView mHeadImage;
    private TextView mNameText;// 主题名
    private TextView mDescText;// 描述
    // 资讯源部分
    private RelativeLayout mSourceBlockTitle;// 资讯源标题
    private LinearLayout mSourceContainer;
    // 讨论部分
    private RelativeLayout mDiscussBlockTitle;// 讨论标题
    private AdapterInfo mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mSubjectId = getArguments().getInt(XoneConsts.BUNDLE_KEY.SUBJECT_ID, -1);
        mSubjectName = getArguments().getString(XoneConsts.BUNDLE_KEY.SUBJECT_NAME);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mLoadingList = (LoadingListView)View.inflate(getActivity(), R.layout.view_loading_listview,
                null);
        mLoadingList.disablePullToRefresh();
        mLoadingList.setOnLoadingListener(new OnLoadingListener() {

            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoading() {
                mCurrentPage = 1;
                mSubjectInfoTid = XoneService.getInstance().doGetSubjectInfoList(mSubjectId, mCurrentPage, XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT);
            }

            @Override
            public void onLoadingMore() {
                mCurrentPage++;
                mSubjectInfoTid = XoneService.getInstance().doGetSubjectInfoList(mSubjectId, mCurrentPage, XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT);
            }
        });
        // 头图
        View headImage = View.inflate(getActivity(), R.layout.view_subject_head, null);
        mHeadImage = (LoadingImageView)headImage.findViewById(R.id.subject_head_image);
        int width = getActivity().getResources().getDisplayMetrics().widthPixels;
        mHeadImage.setServerClipSize(width, 0);// 设置服务器裁剪大小
        mNameText = (TextView)headImage.findViewById(R.id.subject_name);
        mNameText.setText(mSubjectName);
        mDescText = (TextView)headImage.findViewById(R.id.subject_desc);
        // 资讯源
        mSourceBlockTitle = (RelativeLayout)View.inflate(getActivity(),
                R.layout.view_pgrecomm_divider_title, null);
        ((TextView)mSourceBlockTitle.getChildAt(0)).setText(getString(
                R.string.pgsubject_has_x_source, 0));// 初始化标题0个
        mSourceContainer = new LinearLayout(getActivity());
        mSourceContainer.setOrientation(LinearLayout.VERTICAL);
        // 讨论
        mDiscussBlockTitle = (RelativeLayout)View.inflate(getActivity(),
                R.layout.view_pgrecomm_divider_title, null);
        ((TextView)mDiscussBlockTitle.getChildAt(0)).setText(getString(
                R.string.pgsubject_discuss_of_this_subject, mSubjectName));// 初始化标题

        // add views
        mLoadingList.getRefreshableView().addHeaderView(headImage);
        mLoadingList.getRefreshableView().addHeaderView(mSourceBlockTitle);
        mLoadingList.getRefreshableView().addHeaderView(mSourceContainer);
        mLoadingList.getRefreshableView().addHeaderView(mDiscussBlockTitle);
        mAdapter = new AdapterInfo(getActivity(), null);
        mLoadingList.setAdapter(mAdapter);

        XoneService.getInstance().addListener(mCallBack);
        mSubjectTid = XoneService.getInstance().doGetSubjectDetail(mSubjectId, mSubjectName);
        return mLoadingList;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLoaderManager().initLoader(0, null, this);
        mLoadingList.load();
    }

    @Override
    public void onDestroy() {
        XoneService.getInstance().removeListener(mCallBack);
        super.onDestroy();
    }

    private XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onGetSubjectDetail(int transactionId, protocol.meta.Subject subject) {
            if (mSubjectTid == transactionId && subject != null) {
                mSubject = subject;
                mSubjectName = subject.subjectName;
                mHeadImage.setLoadingImage(subject.headImageUrl);
                mNameText.setText(mSubjectName);
                mDescText.setText(subject.subjectDesc);
                if (subject.sourceList != null && subject.sourceList.size() > 0) {
                    // 设置资讯源
                    ((TextView)mSourceBlockTitle.getChildAt(0)).setText(getString(
                            R.string.pgsubject_has_x_source, subject.sourceList.size()));
                    ((TextView)mDiscussBlockTitle.getChildAt(0)).setText(getString(
                            R.string.pgsubject_discuss_of_this_subject, mSubjectName));// 初始化标题
                    for (int i = 0; i < subject.sourceList.size(); i++) {
                        Source source = subject.sourceList.get(i);
                        View sourceItem = View.inflate(getActivity(), R.layout.view_source_item,
                                null);
                        RenderSourceView render = new RenderSourceView(sourceItem);
                        render.renderView(getActivity(), source, i == 0,
                                i == subject.sourceList.size() - 1);
                        sourceItem.setTag(render);
                        mSourceContainer.addView(sourceItem);
                    }
                    mLoadingList.resizeLoadingView();
                }
            }
        };

        @Override
        public void onGetSubjectDetailError(int transactionId, int errCode, String err) {

        };

        @Override
        public void onSubscribe(int transactionId, int[] subjectIdAndSourceId) {
            // 有订阅信息，需要更新订阅状态
            int subjectId = subjectIdAndSourceId[0];
            int sourceId = subjectIdAndSourceId[1];
            // 更新订阅状态
            if (mSubject == null || mSubject.sourceList == null || mSubject.sourceList.size() == 0)
                return;// 忽略没有资讯源的主题
            if (subjectId > 0) {
                // subjectId > 0,表明是订阅全部
                if (subjectId == mSubject.subjectId) {
                    // 更新该主题下的所有资讯源
                    for (Source source : mSubject.sourceList) {
                        source.isSubscribed = true;
                        source.subscribeCount++;
                        mSubject.mySubCount++;
                        mSubject.subscribeCount++;
                    }
                    // mSubject.mySubCount = mSubject.sourceList.size();
                    for (int i = 0; i < mSourceContainer.getChildCount(); i++) {
                        View child = mSourceContainer.getChildAt(i);
                        RenderSourceView render = (RenderSourceView)child.getTag();
                        render.renderView(getActivity(), mSubject.sourceList.get(i), i == 0,
                                i == mSubject.sourceList.size() - 1);
                    }
                }
            } else {
                // 订阅单个资讯源
                for (Source source : mSubject.sourceList) {
                    if (sourceId == source.sourceId) {
                        // 更新该资讯源
                        source.isSubscribed = true;
                        source.subscribeCount++;
                        mSubject.mySubCount++;
                        mSubject.subscribeCount++;
                        // 更新视图
                        for (int i = 0; i < mSourceContainer.getChildCount(); i++) {
                            View child = mSourceContainer.getChildAt(i);
                            TextView sourceNameText = (TextView)child
                                    .findViewById(R.id.source_name);
                            if (source.sourceName.equals(sourceNameText.getText().toString())) {
                                // 寻找匹配的sourceItem进行刷新
                                RenderSourceView render = (RenderSourceView)child.getTag();
                                render.renderView(getActivity(), mSubject.sourceList.get(i),
                                        i == 0, i == mSubject.sourceList.size() - 1);
                            }
                        }
                        break;// 找到之后就没必要继续查找了
                    }
                }
            }
        };

        @Override
        public void onUnsubscribe(int transactionId, int sourceId) {
            // 更新订阅状态
            if (mSubject == null || mSubject.sourceList == null || mSubject.sourceList.size() == 0)
                return;// 忽略没有资讯源的主题
            // 取消订阅资讯源
            for (Source source : mSubject.sourceList) {
                if (sourceId == source.sourceId) {
                    // 更新该资讯源
                    source.isSubscribed = false;
                    source.subscribeCount--;
                    mSubject.mySubCount--;
                    mSubject.subscribeCount--;
                    // 更新视图
                    for (int i = 0; i < mSourceContainer.getChildCount(); i++) {
                        View child = mSourceContainer.getChildAt(i);
                        TextView sourceNameText = (TextView)child.findViewById(R.id.source_name);
                        if (source.sourceName.equals(sourceNameText.getText().toString())) {
                            // 寻找匹配的sourceItem进行刷新
                            RenderSourceView render = (RenderSourceView)child.getTag();
                            render.renderView(getActivity(), mSubject.sourceList.get(i), i == 0,
                                    i == mSubject.sourceList.size() - 1);
                        }
                    }
                }
            }
        };

        @Override
        public void onGetSubjectInfoList(int transactionId, boolean hasMore) {
            if (mSubjectInfoTid == transactionId) {
                mLoadingList.onLoadingComplete(hasMore);
            }
        };

        @Override
        public void onGetSubjectInfoListError(int transactionId, int errCode, String err) {
            if (mSubjectInfoTid == transactionId) {
                if (errCode == XoneServiceCode.NETWORK_ERR_COMMON) {
                    mLoadingList.onNoNetwork();
                } else {
                    mLoadingList.onLoadingError();
                }
            }
        };
    };

    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        StringBuilder where = new StringBuilder();
        where.append(AppInfoTable.C_INFOGROUP).append("=")
                .append(ManagerAppInfo.GROUP_SUBJECT_INFO_LIST).append(" AND ")
                .append(AppInfoTable.C_SORTTYPE).append("=").append(mSubjectId).append(" AND ")
                .append(AppInfoTable.C_ACCOUNT).append("='")
                .append(ManagerAccount.getInstance().getCurrentAccountId()).append("'");
        return new CursorLoader(getActivity(), AppInfoTable.CONTENT_URI, ManagerAppInfo.Projection,
                where.toString(), null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
        mAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        mAdapter.swapCursor(null);
    }

}
